package com.cx.mall.cart.service.impl;

import com.cx.mall.cart.mapper.CartMapper;
import com.cx.mall.cart.service.CartService;
import com.cx.mall.common.entity.cart.Cart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Override
    public void save(Cart cart) {
        //如果购物车中有此商品，则更新
        if(cartMapper.existsById(cart.get_id())){
            Cart obj = cartMapper.findById(cart.get_id()).get();
            //如果商品数量大于0，则更新
            obj.setNum(obj.getNum() + cart.getNum());
           cartMapper.deleteById(cart.get_id());
        }
        cartMapper.save(cart);
    }

    @Override
    public List<Cart> list(String userId) {
        Cart cart = new Cart();
        cart.setUserId(userId);

        return cartMapper.findAll(Example.of(cart), Sort.by(Sort.Direction.DESC,"createTime"));


    }

    @Override
    public void deleteByIds(List<String> ids) {
        cartMapper.deleteAllById(ids);
    }
}
